package xhwl.retrofitrx;


import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;

/**
 * 异常处理工厂
 * 主要是解析异常，输出自定义ApiException
 * Created by WZG on 2016/12/12.
 */

public class ExceptionFactory {
    private static final String HttpException_MSG = "网络错误";
    private static final String ConnectException_MSG = "连接超时";
    private static final String JSONException_MSG = "fastjeson解析失败";
    private static final String UnknownHostException_MSG = "无法解析该域名";

    /**
     * 解析异常
     *
     * @param e
     * @return
     */
    public static xhwl.retrofitrx.HttpException analysisExcetpion(Throwable e) {
        xhwl.retrofitrx.HttpException exception = new xhwl.retrofitrx.HttpException(e);
        if(e instanceof ConnectException)
        {
            exception.setCode(HttpCode.CODE_HTTP_CONNECTION_TIMEOUT);
            exception.setMessage("连接超时,请检查当前网络");
        }
        else if(e instanceof SocketTimeoutException)
        {
            exception.setCode(HttpCode.CODE_SOCKET_CONNECTION_TIMEOUT);
            exception.setMessage("请求超时");
        }
        else if ( e instanceof JSONException || e instanceof ParseException) {
            exception.setCode(HttpCode.CODE_JSON_PARSE_ERROR);
            exception.setMessage("json解析错误");
        }else {
            /*未知异常*/
            exception.setCode(HttpCode.CODE_HTTP_EXCEPTION);
            exception.setMessage(e.getMessage());
        }
        exception.printStackTrace();
        return exception;
    }
}
